package com.healthdata.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtUtil {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private long expiration;

    public boolean verifyToken(String token) {
        try {
            token = extractToken(token); // 提取实际token
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            verifier.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            return false;
        }
    }

    public Long getUserIdFromToken(String token) {
        try {
            token = extractToken(token); // 提取实际token
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return Long.valueOf(jwt.getSubject());
        } catch (JWTVerificationException e) {
            return null;
        }
    }

    public String generateToken(Long userId) {
        Algorithm algorithm = Algorithm.HMAC256(secret);
        return JWT.create()
                .withSubject(String.valueOf(userId))
                .withExpiresAt(new Date(System.currentTimeMillis() + expiration))
                .sign(algorithm);
    }

    // 新增方法：提取实际token（兼容带Bearer和不带Bearer的情况）
    private String extractToken(String token) {
        if (token == null) {
            return null;
        }
        // 如果以Bearer开头，去掉Bearer前缀
        if (token.startsWith("Bearer ")) {
            return token.substring(7);
        }
        // 否则直接返回原token
        return token;
    }
}